package cn.alm.spring03tx.service;

import cn.alm.spring03tx.dao.AccountDao;
import cn.alm.spring03tx.dao.BookDao;
import cn.alm.spring03tx.entity.Book;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class UserService {

    @Resource
    private BookDao bookDao;

    @Resource
    private AccountDao accountDao;

    @Transactional
    public void buyBook(Integer userId, Integer bookId, Integer num) {
        // 获取书籍
        Book book = bookDao.getBookById(bookId);
        if (book == null) {
            System.out.println("书籍不存在");
            throw new RuntimeException("书籍不存在");
        }
        // 计算出总花费
        BigDecimal cost = book.getPrice().multiply(new BigDecimal(num));
        // 减少库存
        bookDao.updateBookStockById(bookId, num);
        // 减少账户
        accountDao.updateAccountById(userId, cost);
    }

}
